package com.lry.basic.netty.protocol.server;

import com.lry.basic.netty.protocol.struct.Header;
import com.lry.basic.netty.protocol.struct.NettyMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/9/12
 */
public class ServerHandler extends ChannelInboundHandlerAdapter{
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("--------通道激活------------");
    }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMsg request = (NettyMsg)msg;
        System.out.println("Server receive message from Client: " + request.getBody());
        NettyMsg response = new NettyMsg();
        Header header = new Header();
        header.setSessionId(2002L);
        header.setPriority((byte)2);
        header.setType((byte)1);
        response.setHeader(header);
        response.setBody("我是响应数据: " + request.getBody());
        ctx.writeAndFlush(response);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("--------数据读取完毕----------");
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        System.out.println("--------服务器数据读异常----------: ");
        cause.printStackTrace();
        ctx.close();
    }
}
